package com.jasonchoi.redisqueue.queue;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 实例化消费者 加入监听
 * @Author: JasonChoi
 * @Date: 2020/3/16 9:52
 */
@Component
public class RedisQueueStarter implements InitializingBean, ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void afterPropertiesSet() throws Exception {
        Map<String, IRedisQueueConsumer> beans = applicationContext.getBeansOfType(IRedisQueueConsumer.class);
        if (beans != null) {
            ExecutorService executorService = Executors.newFixedThreadPool(beans.size());
            for (Map.Entry<String, IRedisQueueConsumer> entry : beans.entrySet()) {
                executorService.execute(new RedisQueueHandler(entry.getValue()));
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        RedisQueueStarter.applicationContext = applicationContext;
    }

    public static <T> T getBean(Class<T> clazz){
        return RedisQueueStarter.applicationContext.getBean(clazz);
    }
}
